package rexsee.core.storage;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.utilities.Json;
import rexsee.core.utilities.Utilities;
import android.content.Context;
import android.content.res.AssetManager;

public class RexseeAsset implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Asset";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return this;
	}

	private final Browser mBrowser;
	private final Context mContext;

	public RexseeAsset(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
	}

	public String list(String path) {
		path = cleanPath(path);
		AssetManager am = mContext.getResources().getAssets();
		try {
			return Json.toJson(am.list(path));
		} catch (IOException e) {
			return "[]";
		}
	}
	public boolean exists(String path) {
		path = cleanPath(path);
		AssetManager am = mContext.getResources().getAssets();
		try {
			InputStream is = am.open(path);
			if (is != null) {
				is.close();
				return true;
			} else return false;
		} catch (IOException e) {
			return false;
		}
	}
	public String getContent(String path, String encode) {
		path = cleanPath(path);
		try {
			byte[] bytes = Utilities.getAssetContent(mContext, path);
			return (bytes == null) ? "" : new String(bytes, encode);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	public long getSize(String path) {
		path = cleanPath(path);
		try {
			AssetManager am = mContext.getResources().getAssets();
			InputStream in = am.open(path);
			return in.available();
		} catch (Exception e) {
			return -1;
		}
	}
	public boolean copyToExternalStorage(String path, String sdPath) {
		path = cleanPath(path);
		return Utilities.copyAssetToExternalStorage(mContext, path, sdPath);
	}

	public String cleanPath(String path) {
		if (path.toLowerCase().startsWith("file:///android_asset/")) {
			return path.substring(22);
		} else {
			return path;
		}
	}

}
